<!--
 * @Author: wang_sheshe
 * @Date: 2021-05-18 15:21:27
 * @LastEditTime: 2021-07-29 08:48:41
 * @Description: 新建巡视任务
-->
<template>
	<article class="bg_4dbfae tourTaskPage addTask">
		<!-- 头组件 -->
        <van-nav-bar title="创建巡视任务" left-text="" left-arrow @click-left="back" fixed>
			<!-- <template slot="right" @click="loginOutApp">
				<div class="parent-circle">
					<div class="child-circle"></div>
				</div>
            </template> -->
        </van-nav-bar>
        <!-- content -->
		<div style="flex: 1; overflow: auto;margin-top: 50px;">
			<van-field 
				label="变电站:"  
				placeholder="请选择" 
				readonly 
				required  
				input-align="right"
				@click="showSubstation=true"
				right-icon="arrow" 
				v-model="taskData.substationName"
				@click-right-icon="showSubstation=true"/>
			<van-field 
				label="电压等级:" 
				placeholder="请输入" 
				required  
				readonly
				input-align="right"
				v-model.trim="taskData.voltageLevel" 
			/>
			
			<van-field 
				label="巡视类型:" 
				placeholder="请选择" 
				required 
				readonly 
				input-align="right"
				@click="showTourType=true"
				v-model="taskData.patrolTypeName" 
				right-icon="arrow"
				@click-right-icon="showTourType=true"/>

			<van-field 
			label="要求完成时间:" 
			placeholder="请选择" 
			required 
			readonly 
			input-align="right"
			@click="isDatePicker=true"
			v-model="taskData.requireFinishTime"
			>
				<template slot="right-icon">
					<van-image style="position: relative;top: 5px;"
					@click="isDatePicker=true"  width="24" height="24" :src="url.time"/>
				</template>
			</van-field>

			<van-row style="padding: 0 15px;color:#666;margin-top: 15px;" class="font14">备注:</van-row>
			<div style="margin: 15px;border-radius: 5px;">
				<van-field class="textarea-content" v-model.trim="taskData.remark" rows="2" autosize type="textarea" maxlength="256"
                    placeholder="请输入备注" show-word-limit />
			</div>

			<van-cell :border="false" title="巡视人员">
				<template slot="right-icon">
					<van-image class="imgSize" width="20" height="20"   @click="showTourPerson=true" :src="url.add" />
				</template>
				<template slot="label">
					<van-button v-for="(item,index) in selTourPerson" :key="index" round type="default" class="active" size="mini">{{item.userName}}</van-button>
				</template>
			</van-cell>
            <van-field 
				label="巡视设备" 
				maxlength="10"  
				placeholder="" 
				:border="false" 
				v-model.trim="taskData.DEVICE"
			/>    
			<div style="margin: 5px 15px;">
				<van-button round type="default"
				@click="deviceStyle='0'" :class="{active: deviceStyle == '0'}" size="mini">全站设备</van-button>
				<van-button v-if="taskData.patrolTypeName =='特殊巡视'" round type="default" :class="{active: deviceStyle == '1'}" size="mini" @click="conDeviceTypeBtn">指定类型</van-button>
				<van-button v-if="taskData.patrolTypeName =='特殊巡视'" round type="default" :class="{active: deviceStyle == '2'}" size="mini" @click="conDeviceBtn">指定设备</van-button>
			</div>
			
			<!-- 显示选中设备列表-->
			<van-collapse :border="false" v-if="deviceStyle == '2'" v-model="activeNames" class="collapse">
				<van-collapse-item :border="false" :name="typeItem.bayId" v-for="(typeItem,ii) in seldeviceList" :title="typeItem.bayName" :key="ii">
				  <!-- 间隔下设备列表 -->
				  	<van-cell :title="item.deviceName"
					  v-for="(item,index) in typeItem.deviceList"
					  clickable
					  :key="index"            
					>
						<van-icon slot="right-icon" name="clear" size="1.5em" color="#37be9c" @click="delDevice(ii,index)" />
					</van-cell>
				</van-collapse-item>
			</van-collapse>

			<!-- 显示设备类型-->
			<van-cell-group v-if="deviceStyle == '1'">
				<van-cell :title="deviceType.deviceTypeName"
					v-for="(deviceType,index) in devTypeList"
					clickable
					:key="index"            
				>
					<van-icon slot="right-icon" name="clear" size="1.5em" color="#37be9c" @click="delDeviceType(index)" />
				</van-cell>
			</van-cell-group>
		</div>
		<!-- 按钮-->
		<van-row class="btn-wrapper" style="text-align: center;">
			<van-button type="primary" size="small" class="c" @click="confirm">完成</van-button>
		</van-row>

		<!-- 设备类型选择器 -->
		<van-popup class="selSub" round close-on-click-overlay v-model="isShowSelect" position="bottom" @close="isShowSelect=false">
			<SelDeviceType 
			:devTypeList="devTypeList"
			 :subId = "taskData.substationId"
			 @close="isShowSelect=false"
			 @deviceType="selDeviceTypeBtn"
			></SelDeviceType>
		</van-popup>

		<!-- 变电站 -->
		<van-popup class="selSub" round close-on-click-overlay v-model="showSubstation" position="bottom" @close="showSubstation=false">
			<selSubstation @close="showSubstation=false"
			:subId="subId"
			@selected="selSublist"></selSubstation>
		</van-popup>

		<!-- 时间类型选择器 -->
		<van-popup round close-on-click-overlay v-model="isDatePicker" position="bottom" @close="isDatePicker=false">
			<van-datetime-picker v-model="currentDate" title="选择时间" @confirm="onConfirm" 
			:min-date="minDate"
			:formatter="formatter"
  			:max-date="maxDate"
			@cancel="isDatePicker=false" type="datetime">
			</van-datetime-picker>
		</van-popup>

		<!-- 反馈组件 巡视类型-->
        <van-action-sheet title="选择巡视类型" 
			cancel-text="取消"
			@cancel="showTourType=false"
            v-model="showTourType"
            :actions="tourTypeList"
            @select="tourTypeBtn"
		/>
		
		<!-- 反馈组件 巡视人员-->
		<van-popup class="selSub" round close-on-click-overlay v-model="showTourPerson" position="bottom" @close="showTourPerson=false">
			<selPople :userList="selTourPerson" @comfirmPerson="selTourPersonBtn" @closePersonPage="showTourPerson=false"></selPople>
		</van-popup>

		<!-- 反馈组件 指定设备-->
		<van-popup class="selPerson" round v-model="isShowDev" position="bottom" @close="showPerson=false">
			<SelectTourDevice 
			:subId = "taskData.substationId"
			:seldeviceList = "seldeviceList"
			@selDevice="selDeviceBtn"
			@close="isShowDev=false"
			></SelectTourDevice>
		</van-popup>

	</article>
</template>

<script type="text/javascript">
	import { Tabbar, TabbarItem ,Tag } from 'vant';
	import Util from "@/utils/util" 
	import {mapGetters} from 'vuex'
	import selSubstation  from "@/components/SelectSubstation" 
	import selPople  from "@/components/SelPeople.vue"
	import SelectTourDevice  from "@/components/SelectTourDevice"
	import SelDeviceType  from "@/components/SelDeviceType"
	import {addTourTask,editTourTask} from '../../api/tourTask';
	export default {
		name: 'DefectManage',
		components: {
			selSubstation,
			selPople,
			SelectTourDevice,
			SelDeviceType
		},
		data() {
			return {
				finished:true,
				loading:false,
				btnValue:document.querySelector(".van-icon-cross"),
				//subName:"",//选中变电站名称
				//subId:"",//选中变电站id
				showTourType:false,//巡视类型显示
				showTourPerson: false,//显示巡视人员
				deviceStyle: "0",//设备选择：0-全站设备 1-指定类型 2-指定设备
				taskData:{
					requireFinishTime: "",
					voltageLevel: "",//电压等级
					remark: "",//备注
					substationId: "",//变电站ID
					substationName: "",//变电站名称
					patrolTypeName: "",//巡视类型名称
					patrolTypeNameId: "",//巡视类型ID
				},
				devTypeList:[],//选中的设备类型名称
				seldeviceList:[],//选中的设备名称
				selTourPerson: [],//选择巡视人员
                isDatePicker:false,
				showPicker:false,
				showSubstation:false,//显示变电站
                currentDate:new Date(),//选择的日期
				activeNames:[],
				tourTypeList: [],
				deviceTypeShow: true,//设备类型
				deviceShow: true,
				minDate: new Date(new Date().getFullYear()-2,new Date().getMonth()+1,new Date().getDay()),
				maxDate: new Date(new Date().getFullYear()+2,new Date().getMonth()+1,new Date().getDay()),
				deviceTypeList: [{ //设备类型列表
					code:1,
					codeName: '一号主变',
					check: false, //当前设备是否选中
					deviceList: [{
					check: false, //当前设备是否选中
					deviceTypeId:'',
					deviceId: '0301',
					deviceName: '一号主变A相'
					}] //下级设备列表
				}],  
				valueKey:"10",
				isShowSelect:false,//指定设备类型显示开关
				isShowDev:false,//指定设备显示开关
				url: {
					add: require('../../../../assets/img/mainIndex/add.png'),
					time: require("../../../../assets/img/mainIndex/time.png"),
				},
				userInfo:{}
			}
		},
		
		computed: {
			...mapGetters(["subId","subName","powerLevelName"])
		},
		
		methods: {
			confirm(){
				this.isCheckedParam();
			},
			/**
			* @description: 选择指定设备类型
			* @param {*}
			* @return {*}
			*/
			conDeviceTypeBtn() {
				if(Util.baseUtil.isEmptyString(this.taskData.substationId)) {
					this.$Toast.fail("请选择变电站!")
					return;
				}
				this.seldeviceList = [];//清空设备
				this.deviceStyle='1';
				this.isShowSelect=true;
			},
			/**
			* @description: 选择指定设备
			* @param {*}
			* @return {*}
			*/
			conDeviceBtn() {
				if(Util.baseUtil.isEmptyString(this.taskData.substationId)) {
					this.$Toast.fail("请选择变电站!")
					return;
				}
				this.devTypeList = [];//清空设备类型
				this.isShowDev=true;
				this.deviceStyle='2'
			},
			/**
			* @description: 参数校验
			* @param {*}
			* @return {*}
			*/
			isCheckedParam() {
				if(Util.baseUtil.isEmptyString(this.taskData.substationId)) {
					this.$Toast.fail("请选择变电站!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.voltageLevel)) {
					this.$Toast.fail("请填写电压等级!")
					return;
				}
				
				if(Util.baseUtil.isEmptyString(this.taskData.patrolTypeNameId)) {
					this.$Toast.fail("请选择巡视类型!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.taskData.requireFinishTime)) {
					this.$Toast.fail("请选择要求完成时间!")
					return;
				}
				if(this.selTourPerson.length == 0) {
					this.$Toast.fail("请选择巡视人员!")
					return;
				}
				if(this.deviceStyle == "1") {
					if(this.devTypeList.length==0) {
						this.$Toast.fail("请选择指定类型设备!")
						return;
					}
				}
				if(this.deviceStyle == "2") {
					if(this.seldeviceList.length==0) {
						this.$Toast.fail("请选择指定设备!")
						return;
					}
				}
				this.addTask();
			},
			/**
			* @description: 创建任务
			* @param {*}
			* @return {*}
			*/
			addTask() {
				var self = this,devicelist=[],devTypeListId=[],userList=[];
				this.seldeviceList.map(item => {
					item.deviceList.map(device => {
						devicelist.push({
							bayId: device.bayId,
							bayName: device.bayName,
							deviceId: device.deviceId,
							deviceName: device.deviceName,
							//phase: device.phase,
						})
					})
				})
				//设备类型
				this.devTypeList.map(item => {
					devTypeListId.push(item.deviceTypeId)
				})
				this.selTourPerson.forEach(item => {
					userList.push({
						coordinate: "",
						patrolStaffId: item.userId,//巡视人员id
						patrolStaffName: item.userName,
					})
				})
				
				var params = {
					//deviceList: devicelist,//指定设备
					//deviceType: devTypeListId,//指定设备类型
					deviceChoiceFlag: this.deviceStyle,//设备类型 0
					remark: this.taskData.remark,//
					patrolType: this.taskData.patrolTypeNameId,//巡视类型code
					patrolTypeName:this.taskData.patrolTypeName,//巡视类型名称
					substationId:this.taskData.substationId,
					substationName:this.taskData.substationName,
					patrolTeam: this.userInfo.orgId,
					patrolTeamName: this.userInfo.orgName,
					userId: this.userInfo.userId,
					userList: userList,//巡视人员
					voltageLevel: this.taskData.voltageLevel,//电压等级
				};
				if(this.deviceStyle == 1) {//指定设备类型
					params.deviceTypeIdList = devTypeListId
				}
				if(this.deviceStyle == 2) {//指定设备
					params.deviceList= devicelist//指定设备
				}
				if(this.taskData.taskId) {
					params.id = this.taskData.taskId;
				}
				params.requireFinishTime = new Date(this.currentDate).getTime();
				console.log("params",params)
				this.$Toast.loading({
						duration: 0,//展示时长 0不会消失
						message: "巡视任务创建中...",
						forbidClick: true,//是否禁止背景点击
						overlay: true//是否显示背景遮罩层
					})
				//编辑页面
				editTourTask(params).then(data => {
					self.$Toast.clear();
					if(data.success) {
						self.$Toast.success(data.msg)
						self.$router.push({name:"tourTaskIndex",params:{}})
					}else{
						self.$Toast.fail(data.msg)
					}
				}).catch(err => {
					self.$Toast.fail(err)
				})
			},
			//时间确认按钮
            onConfirm(val){
				this.isDatePicker = false;
            	this.taskData.requireFinishTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
            },
			/**
			 * 返回
			 */
			back(){
				history.go(-1)
			},
			/**
			* @description: 退出系统
			*/
			loginOutApp(){
				
			},
			/**
			* @description: 选择变电站
			* @param {*}
			* @return {*}
			*/
			selSublist(selSub) {
				console.log("selSub",selSub)
				this.taskData.substationId = selSub.substationId;
				this.taskData.substationName = selSub.substationName;
				//电压等级
				this.taskData.voltageLevel = selSub.powerLevelName;
				this.showSubstation = false;
			},
			//选择巡视类型
			tourTypeBtn(val) {
				this.showTourType = false;
				this.taskData.patrolTypeName = val.name;
				this.taskData.patrolTypeNameId = val.code;
			},
			//选择巡视人员
			selTourPersonBtn(selPerson) {
				this.showTourPerson = false;
				console.log("selPerson",selPerson)
				this.selTourPerson = selPerson;
			},
			//删除选中设备
			delDevice(index,devIndex) {
				this.seldeviceList.forEach((item,i) => {
					if(this.seldeviceList[index].bayId == item.bayId) {
						item.deviceList.splice(devIndex,1)
					}
					if(item.deviceList && item.deviceList.length == 0){
						this.seldeviceList.splice(i,1)
					}
				})			
				console.log("seldeviceList====",this.seldeviceList)
			},
			//删除选中的设备类型
			delDeviceType(deviceId) {
				this.devTypeList.splice(deviceId,1);
			},
			//选中指定设备
			selDeviceBtn(device) {
				console.log("选中指定设备",device)
				this.isShowDev = false;
				this.seldeviceList = JSON.parse(JSON.stringify(device));
			},
			//选中指定设备类型
			selDeviceTypeBtn(device) {
				console.log("选中指定设备类型",device)
				this.isShowSelect = false;
				this.devTypeList = JSON.parse(JSON.stringify(device));;
			},
			//渲染数据
			renderData(taskInfo) {
				taskInfo.userList.map(item => {
					this.selTourPerson.push({
						userId: item.patrolStaffId,
						userName: item.patrolStaffName
					})
				})
				this.taskData.remark = taskInfo.remark;//备注
				this.taskData.voltageLevel = taskInfo.voltageLevel;//电压等级
				this.taskData.substationName = taskInfo.substationName;
				this.taskData.substationId  = taskInfo.substationId;
				this.taskData.patrolTypeName = taskInfo.patrolTypeName;//巡视类型名称
				this.taskData.patrolTypeNameId = taskInfo.patrolType;//巡视类型id
				this.taskData.requireFinishTime = 
				Util.DateUtil.getFormatDateByLong(taskInfo.requireFinishTime,'yyyy-MM-dd hh:mm');
				//指定类型 0全部设备  1.指定类型  2.指定设备
				this.deviceStyle = taskInfo.patrolScope;
				this.devTypeList = taskInfo.deviceTypeList;//设备类型
				this.seldeviceList = [];
				if(taskInfo.deviceList && taskInfo.deviceList.length > 0) {
					var obj = [];
					for(var i in taskInfo.deviceList) {
						if(obj.indexOf(taskInfo.deviceList[i].bayId) === -1) {
							this.seldeviceList.push({
								bayName: taskInfo.deviceList[i].bayName,
								bayId: taskInfo.deviceList[i].bayId,
								deviceList:[taskInfo.deviceList[i]]
							})
							obj.push(taskInfo.deviceList[i].bayId);
						}else{
							for(var j in this.seldeviceList) {
								if(this.seldeviceList[j].bayId == taskInfo.deviceList[i].bayId) {
									this.seldeviceList[j].deviceList.push(taskInfo.deviceList[i]);
									break;
								}
							}
						}
					}
				}
				console.log("this.seldeviceList",this.seldeviceList)
			},
			//日期格式
			formatter(type, val) {
				if (type === 'year') {
					return val + '年';
				}
				if (type === 'month') {
					return val + '月';
				}
				if (type === 'day') {
					return val + '日';
				}
				if (type === 'hour') {
					return val + '时';
				}
				if (type === 'minute') {
					return val + '分';
				}
				return val;
			}
		},
		mounted() {
			var userInfo = localStorage.getItem("userInfo");
			this.userInfo = JSON.parse(userInfo);
			var taskInfo = this.$route.params.taskInfo;
			console.log("taskInfo",taskInfo)
			if(taskInfo && taskInfo.id) {//编辑任务
				this.renderData(taskInfo);
			}else{
				this.taskData.substationName = this.subName;
				this.taskData.substationId  = this.subId;
				this.taskData.voltageLevel = this.powerLevelName;
			}
			//巡视类型
			this.tourTypeList = Util.baseUtil.getSpecialCode("JX_TOUR_TYPE");
			console.log("tourTypeList",this.tourTypeList);
		},
	}
</script>

<style scoped>
	article {
		display: flex;
		flex-direction: column;
		height: 100vh;
        font-family: 微软雅黑;
        background: #ffffff;
	}
	.addTask .active{
		color: #17b49b !important;
		background: #e2f4f1 !important;
	}
    .addTask .van-button--primary {
		background-color: #17B49B;
        border: 0.02667rem solid #17B49B;
        color: white;
		width: 138px;
        margin: 0 auto;
    }
	.addTask .lineGray{
		height: 8px;
		background-color: #F5F6FA;
		border-radius: 5px;
		margin: 10px;
	}
	.addTask /deep/ .van-checkbox-part{
		display: inline;
	}
	.addTask /deep/ .van-checkbox__icon{
		display: inline;
	}
	.addTask /deep/ .van-checkbox__icon .van-icon{
		display: inline;
	}
	.subClass /deep/ .van-nav-bar__text{
		font-size: 16px !important;
	}
	.content .van-field__body{
		border: 1px solid #E2E2E2;
	}
	.selSub{
		width:100%;height:100%;
	}
	.selPerson{
		height:100%;width:100%;
	}  
	.textarea-content{
		border: 1px solid #E2E2E2;color:#999;
	}
	/deep/ .van-field__label{
		width: 7.5rem;
	}
</style>
